<template>
  <div :class="prefixCls">
    <div ref="editor" class="editor-wrapper"></div>
  </div>
</template>

<script>
import WEditor from 'wangeditor'
import {upload} from "@/api/common";
export default {
  name: 'WangEditor',
  props: {
    prefixCls: {
      type: String,
      default: 'ant-editor-wang'
    },
    // eslint-disable-next-line
    values: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      editor: null,
      editorContent: null
    }
  },
  mounted () {
    this.initEditor()
    this.$watch('values', e => {
      if (e) {
        this.editorContent = e
        this.editor.txt.html(e)
      }
    }, {
      deep: true,
      immediate: true,
    })
    this.$watch('disabled', e => {
      if (e) {
        this?.editor.disable()
      } else {
        this?.editor.enable()
      }
    }, {
      deep: true,
      immediate: true,
    })
  },
  methods: {
    initEditor () {
      this.editor = new WEditor(this.$refs.editor)
      this.editor.config.onchangeTimeout = 500
      this.editor.config.onchange = (html) => {
        this.editorContent = html
        this.$emit('change', {
          html: this.editor.txt.html(),
          text: this.editor.txt.text(),
        })
      }
      this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
        resultFiles.forEach(item => {
          this.uploadFile(item, insertImgFn)
        })
      }
      this.editor.config.onblur = newHtml => {
        this.$emit("blur", newHtml)
      }
      this.editor.config.onfocus = newHtml => {
        this.$emit("blur", newHtml)
      }
      this.editor.create()
    },
    uploadFile(e, func) {
      const formatData = new FormData()
      formatData.append('file', e)
      upload(formatData).then(ret => {
        if (ret.success) {
          formatData.delete('file');
          console.log(this.$staticPrefix(ret.data));
          func(this.$staticPrefix(ret.data));
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ant-editor-wang {
  .editor-wrapper {
    text-align: left;
  }
}
</style>
